package com.example;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.BodyExtractor;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by teeyoung on 17/9/22.
 */
@Component
public class EchoHandler {

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    public Mono<ServerResponse> echo(ServerRequest request) {
        boolean isGet = HttpMethod.GET.equals(request.method());
        boolean isPost = HttpMethod.POST.equals(request.method());
        List<String> name = null ;
        if (isGet){
            name = request.body((serverHttpRequest, context) -> {
                List<String> names = serverHttpRequest.getQueryParams().get("name");
                return names;
            });
        }else if(isPost){
            // Flux<String> stringFlux = request.bodyToFlux(String.class);          flux request 信息
            name = request.bodyToFlux(String.class).toStream().collect(Collectors.toList());
        }
        System.out.println(atomicInteger.getAndIncrement());
        List<String> data = name;
        if (!CollectionUtils.isEmpty(data))
            data.forEach(System.out::println);

        return ServerResponse.ok()
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(Mono.create(stringMonoSink -> stringMonoSink.success("hello, " + data)), String.class);


    }

}